package com.app.couponsharelife.ui.main.home.fragment

import android.content.Intent
import android.graphics.Paint
import android.graphics.drawable.AnimationDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.app.couponsharelife.R
import com.app.couponsharelife.base.LazyFragment
import com.app.couponsharelife.data.bean.*
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.listener.MyMultiPurposeListener
import com.app.couponsharelife.ui.main.home.HomeFragment
import com.app.couponsharelife.ui.main.home.good.GoodDetailActivity
import com.app.couponsharelife.ui.main.home.search.HomeSearchActivity
import com.app.couponsharelife.utils.DataUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.base_refresh_head.*
import kotlinx.android.synthetic.main.choiceness_rvitm.view.*
import kotlinx.android.synthetic.main.fragment_choiceness.*
import kotlinx.android.synthetic.main.fragment_home_general.*
import kotlinx.android.synthetic.main.popup_homeclass_rvitm.view.*
import kotlinx.android.synthetic.main.rvitem_home_hottop.view.*
import java.text.DecimalFormat
import java.util.HashMap

/**
 *Created by xct on 2019/4/13
 *Description:首页普通分类页面
 */
class HomeGeneralClassFragment:LazyFragment(),View.OnClickListener {
    private var classList= arrayListOf<HomeClassBean>()
    private var goodsList= arrayListOf<TaobaoGoodBean>()
    private var myAdapter:MyAdapter?=null
    private var myClassAdapter:MyClassAdapter?=null
    private var myHomeClassBean:HomeClassBean?=null
    private var favoritesID=""
    private var sequenceType=""
    private var isAsc=false
    private var pageIndex=1
    private var clickIndex=1
    private var isScrolTop=false
    private var homeFragment:HomeFragment?=null
    private var keyword=""
    companion object {
        private val HOLDER_TYPE_TOP=0
        private val HOLDER_TYPE_TOP1=1
        private val HOLDER_TYPE=2
        fun newInstance(homeClassBean: HomeClassBean): HomeGeneralClassFragment {
            val fragment = HomeGeneralClassFragment()
            val bundle= Bundle()
            bundle.putParcelable("Data",homeClassBean)
            fragment.arguments =bundle
            return fragment
        }
    }
    override val viewLayoutId: Int
        get() = R.layout.fragment_home_general

    override fun initViews() {
        homeFragment=parentFragment as HomeFragment
        myHomeClassBean=arguments!!.getParcelable("Data")
        if (myHomeClassBean!=null) {
            favoritesID = (myHomeClassBean!!.id?:0).toString()
            keyword = myHomeClassBean!!.keyWord ?: ""
            setRefresh()
            val gridLayoutManager=GridLayoutManager(context,2)
            gridLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
                override fun getSpanSize(position: Int): Int {
                    return if (position == 0||position == 1) {
                        2
                    } else {
                        1
                    }
                }
            }
            homeGeneral_rv.layoutManager=gridLayoutManager
            myAdapter=MyAdapter()
            homeGeneral_rv.adapter=myAdapter
            homeGeneral_tvQB.setOnClickListener(this)
            homeGeneral_tvXL.setOnClickListener(this)
            homeGeneral_tvJG.setOnClickListener(this)
            homeGeneral_rv.addOnScrollListener(object :RecyclerView.OnScrollListener(){

                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                    if (RecyclerView.SCROLL_STATE_IDLE==newState){
                        homeFragment?.visibilityAnim()
                    }else if(RecyclerView.SCROLL_STATE_SETTLING==newState){
                        //Log.e("eeeee","惯性滑动")
                    }else{
                        homeFragment?.goneAnim()
                    }

                }

                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    val index=(recyclerView.layoutManager as GridLayoutManager)?.findFirstVisibleItemPosition()
                    if (index>=1){
                        homeGeneral_llclass?.visibility=View.VISIBLE
                    }else{
                        homeGeneral_llclass?.visibility=View.INVISIBLE
                    }
                }
            })
        }else{
            showToastMsg("数据出错！")
        }
    }
    private fun setRefresh(){
        hotsale_refreshimg.setImageResource(R.drawable.anim_refresh)
        val animationDrawable=hotsale_refreshimg.drawable as AnimationDrawable
        homeGeneral_smartrefresh.setEnableNestedScroll(true)
        homeGeneral_smartrefresh.setOnMultiPurposeListener(object : MyMultiPurposeListener {
            override fun headerReleased() {
                animationDrawable.start()
            }

            override fun headerMoving(percent: Float) {
                setAnima(percent)
            }

            override fun headerFinish() {
                hotsale_refreshimg.setImageResource(R.drawable.refresh_0)
                animationDrawable.stop()
            }

            override fun loadMore() {
                getData(false,keyword)
            }

            override fun refresh() {
                pageIndex=1
                getData(true,keyword)
            }

        })
    }
    private fun setAnima(vlaue:Float){
        val layoutParams=hotsale_refreshimg.layoutParams as ConstraintLayout.LayoutParams
        layoutParams.matchConstraintPercentHeight=vlaue/2
        layoutParams.dimensionRatio="0.875:1"
        hotsale_refreshimg.layoutParams=layoutParams
    }
    private fun setIntent(taobaoGoodBean:TaobaoGoodBean){
        val intent = Intent(context, GoodDetailActivity::class.java)
        intent.putExtra("good", taobaoGoodBean)
        startActivity(intent)
    }

    override fun onClick(v: View?) {
        when(v?.id){
            R.id.homeGeneral_tvQB->{
                if (clickIndex!=1){
                    homeGeneral_tvXL.setTextColor(resources.getColor(R.color.black))
                    homeGeneral_tvJG.setTextColor(resources.getColor(R.color.black))
                    homeGeneral_tvQB.setTextColor(resources.getColor(R.color.red_ff038))
                    isAsc=false
                    sequenceType=""
                    pageIndex=1
                    getData(false,keyword)
                }
                clickIndex=1
            }
            R.id.homeGeneral_tvXL->{
                if (clickIndex!=2){
                    homeGeneral_tvXL.setTextColor(resources.getColor(R.color.red_ff038))
                    homeGeneral_tvJG.setTextColor(resources.getColor(R.color.black))
                    homeGeneral_tvQB.setTextColor(resources.getColor(R.color.black))
                    isAsc=false
                    sequenceType="total_sales"
                    pageIndex=1
                    getData(false,keyword)
                }
                clickIndex=2
            }
            R.id.homeGeneral_tvJG->{
                if (clickIndex!=3){
                    homeGeneral_tvXL.setTextColor(resources.getColor(R.color.black))
                    homeGeneral_tvJG.setTextColor(resources.getColor(R.color.red_ff038))
                    homeGeneral_tvQB.setTextColor(resources.getColor(R.color.black))
                    isAsc=true
                    sequenceType="price"
                    pageIndex=1
                    getData(false,keyword)
                }
                clickIndex=3
            }
        }
    }
    override fun lazyLoad() {
        if (favoritesID.isNotEmpty()){
            getClassData()
        }
    }
    private fun getClassData(){
        showProgressDialog("加载中...")
        val map= HashMap<String,String>()
        map["firstId"]=favoritesID
        RetrofitWorker.retrofitWorker.getHomeTwoClass(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<List<HomeClassBean>>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<List<HomeClassBean>>) {
                        if (it.code==200){
                            if (it.data!!.isNotEmpty()){
                                classList.clear()
                                classList.addAll(it.data!!)
                                myClassAdapter!!.notifyDataSetChanged()
                                //homeGeneral_llclass.visibility=View.VISIBLE
                                getData(false,keyword)
                            }
                        }
                        dismissProgressDialog()
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }

                })
    }
    private fun getData(refresh: Boolean,favoritesID:String){
        val map = HashMap<String, String>()
        map["pageNo"]=pageIndex.toString()
        map["pageSize"]="10"
        map["keyword"]=favoritesID
        map["orderByField"]=sequenceType
        map["isAsc"]=isAsc.toString()
        //mViewModel?.freshFavorites(map,true)
        RetrofitWorker.retrofitWorker.getClassifyProduct(map)
                .subscribeOn(Schedulers.io())
                .map { DataUtils().taobaoSearchData(it) }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<SearchTBGoodsListBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<SearchTBGoodsListBean>) {
                        if (it.data!=null){
                            if (pageIndex==1){
                                goodsList.clear()
                            }
                            if (refresh){
                                homeGeneral_smartrefresh.finishRefresh()
                                if (it.data!!.recordss.size>0){
                                    goodsList.addAll(it.data!!.recordss)
                                    myAdapter!!.notifyDataSetChanged()
                                    pageIndex++
                                }else{
                                    homeGeneral_smartrefresh.finishLoadMoreWithNoMoreData()
                                }
                            }else{
                                if (it.data!!.recordss.size>0){
                                    homeGeneral_smartrefresh.finishLoadMore()
                                    goodsList.addAll(it.data!!.recordss)
                                    myAdapter!!.notifyDataSetChanged()
                                    pageIndex++
                                }else{
                                    homeGeneral_smartrefresh.finishLoadMoreWithNoMoreData()
                                }
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (refresh){
                            homeGeneral_smartrefresh.finishRefresh()
                        }else{
                            homeGeneral_smartrefresh.finishLoadMore()
                        }
                        if (e is OtherException){
                            //showToastMsg(e.msg)
                        }else{
                            //Log.e("eeee","----->${e.toString()}")
                            showToastMsg("网络加载出错了！")
                        }
                    }
                })
    }
    private inner class MyClassAdapter:RecyclerView.Adapter<RecyclerView.ViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val view = LayoutInflater.from(context).inflate(R.layout.popup_homeclass_rvitm, parent,false)
            return MyClassHolder(view)
        }

        override fun getItemCount(): Int {
            return classList.size
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (classList.isNotEmpty()){
                if (holder is MyClassHolder){
                    val classBean=classList[position]
                    Glide.with(context!!).asBitmap()
                            .apply(RequestOptions().error(R.drawable.ic_app_place_holder3))
                            .load(Contacts.NEWREMOTE_IMAGE_URL +classBean.bgImg)
                            .into(holder.imageView!!)
                    holder.tvName!!.text=classBean.name?:""
                    holder.itemView.setOnClickListener {
                        //holder.tvName!!.setTextColor(context!!.resources.getColor(R.color.red_ff038))
                        val intent=Intent(context, HomeSearchActivity::class.java)
                        intent.putExtra("KeyWord",classBean.keyWord?:"")
                        intent.putExtra("SearchType","TB")
                        startActivity(intent)
                    }
                }
            }
        }
    }
    private inner class MyAdapter:RecyclerView.Adapter<RecyclerView.ViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return when(viewType){
                HOLDER_TYPE_TOP->{
                    val view= LayoutInflater.from(parent.context).inflate(R.layout.rvitem_home_hottop,parent,false)
                    MyTopHolder(view)
                }
                HOLDER_TYPE_TOP1->{
                    val view= LayoutInflater.from(parent.context).inflate(R.layout.home_goods_sticky_head,parent,false)
                    MyTopHolder1(view)
                }
                else->{
                    val view= LayoutInflater.from(parent.context).inflate(R.layout.choiceness_rvitm,parent,false)
                    MyHolder(view)
                }
            }
        }

        override fun getItemCount(): Int {
            return goodsList.size+2
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (holder is MyTopHolder){
                holder.classRv?.layoutManager=GridLayoutManager(context,4)
                myClassAdapter=MyClassAdapter()
                holder.classRv?.adapter=myClassAdapter
            }else if(holder is MyHolder){
                if (goodsList.isNotEmpty()){
                    val df = DecimalFormat("#0.00")
                    val taobaoGoodBean=goodsList[position-2]
                    holder.goodsTitle!!.text=taobaoGoodBean.title
                    if (taobaoGoodBean.has_coupon){
                        holder.goodsTextQh!!.text="券后"
                        holder.goodsOldPrice!!.text=taobaoGoodBean.zk_final_price
                        holder.goodsCoupon!!.text=String.format("¥%s", df.format(taobaoGoodBean.coupon_price.toDouble()))
                        holder.couponLL!!.visibility=View.VISIBLE
                    }else{
                        holder.goodsTextQh!!.text="抢"
                        holder.couponLL!!.visibility=View.INVISIBLE
                        holder.goodsOldPrice!!.text=taobaoGoodBean.reserve_price
                    }
                    holder.oldpriceType!!.text=taobaoGoodBean.goodsSource+"价"
                    holder.goodsType!!.setImageResource(taobaoGoodBean.userType)
                    holder.goodsAward!!.text="￥${taobaoGoodBean.vip_commission}"
                    holder.goodsPrice!!.text="￥${taobaoGoodBean.final_price}"
                    holder.goodsSales!!.text=taobaoGoodBean.volume
                    holder.shopName!!.text=taobaoGoodBean.shop_title
                    holder.shopType!!.setImageResource(taobaoGoodBean.userType)
                    Glide.with(activity!!).asBitmap()
                            .apply(RequestOptions().error(R.drawable.ic_app_place_holder3))
                            .load(taobaoGoodBean.pict_url)
                            .into(holder.goodsImag!!)
                    holder.itemView.setOnClickListener {
                        setIntent(taobaoGoodBean)
                    }
                }
            }
        }
        override fun getItemViewType(position: Int): Int {
            return when(position){
                0->HOLDER_TYPE_TOP
                1->HOLDER_TYPE_TOP1
                else->HOLDER_TYPE
            }
        }
    }
    private inner class MyTopHolder(itemview:View):RecyclerView.ViewHolder(itemview){
        var classRv:RecyclerView?=null
        init {
            classRv=itemview.homeGeneral_classRV
        }
    }
    private inner class MyTopHolder1(itemview:View):RecyclerView.ViewHolder(itemview){

    }
    private inner class MyHolder(itemview:View):RecyclerView.ViewHolder(itemview){
        var goodsTitle:TextView?=null
        var goodsImag:ImageView?=null
        var goodsOldPrice:TextView?=null
        var goodsPrice:TextView?=null
        var goodsCoupon:TextView?=null
        var goodsAward:TextView?=null
        var goodsSales:TextView?=null
        var goodsType:ImageView?=null
        var couponLL: LinearLayout?=null
        var goodsTextQh:TextView?=null
        var oldpriceType:TextView?=null
        var shopName:TextView?=null
        var shopType:ImageView?=null
        init {
            goodsTitle=itemView.choiceness_rvitm_title
            goodsImag=itemview.choiceness_rvitm_img
            goodsOldPrice=itemview.choiceness_rvitm_oldprice
            goodsPrice=itemview.choiceness_rvitm_price
            goodsCoupon=itemview.choiceness_rvitm_quanprice
            goodsAward=itemview.choiceness_rvitm_jiangprice
            goodsSales=itemview.choiceness_rvitm_yuenumber
            goodsType=itemview.choiceness_rvitm_imgtype
            couponLL=itemview.choiceness_rvitm_llq1
            goodsTextQh=itemView.choiceness_rvitm_qh
            oldpriceType=itemView.choiceness_rvitm_oldpricetype
            shopName=itemview.choiceness_rvitm_tvShopName
            shopType=itemview.choiceness_rvitm_ivGoodsType
            goodsOldPrice!!.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG
        }
    }
    private inner class MyClassHolder(itemview:View):RecyclerView.ViewHolder(itemview){
        var imageView: ImageView?=null
        var tvName: TextView?=null
        init {
            imageView=itemview.rvitme_iv
            tvName=itemview.rvitme_tvName
        }
    }
}